﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.OpenApi.Models;
using NetTaste;
using Newtonsoft.Json;
using RxxAdmin.Common;
using RxxAdmin.Common.Helper;
using RxxAdmin.Common.HttpContextUser;
using RxxAdmin.IServices;
using RxxAdmin.Model.Logs;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace RxxAdmin.Api;

public class GlobalOperationLogFilter : ActionFilterAttribute, IFilterMetadata
{
    private readonly IOperationLogService _operationLogService;
    private readonly IUser _user;

    public GlobalOperationLogFilter(IOperationLogService operationLogService, IUser user)
    {
        _operationLogService = operationLogService;
        _user = user;
    }

    // 实现你的过滤器逻辑
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var resultContext = await next();
        //执行后

        //判断标签是在方法上
        if (resultContext.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor) return;

        //查找标签，获取标签对象
        OperLogAttribute? operLogAttribute = controllerActionDescriptor.MethodInfo
            .GetCustomAttributes(inherit: true)
            .FirstOrDefault(a => a.GetType().Equals(typeof(OperLogAttribute))) as OperLogAttribute;
        //空对象直接返回
        if (operLogAttribute is null) return;

        // 在动作方法执行前的逻辑
        string title = operLogAttribute.Title;
        OperEnum opertype = operLogAttribute.OperType;
        string requestmethod = resultContext.HttpContext.Request.Method;
        string operuser = _user.Name;
        string method = resultContext.HttpContext.Request.Path.Value;
        string requestparam = JsonConvert.SerializeObject(context.ActionArguments);
        string requestresult = "";
        if (resultContext.Result is ContentResult result && result.ContentType == "application/json")
        {
            requestresult = result.Content?.Replace("\r\n", "").Trim();
        }

        if (resultContext.Result is JsonResult result2)
        {
            requestresult = result2.Value?.ToString();
        }

        if (resultContext.Result is ObjectResult result3)
        {
            requestresult = JsonConvert.SerializeObject(result3.Value);
        }
        await _operationLogService.Add(title, opertype, requestmethod, operuser, method, requestparam, requestresult);
    }
}
